package com.example.campussysteam.module.admin.controller;

import com.example.campussysteam.common.log.Log;
import com.example.campussysteam.common.log.OperationType;
import com.example.campussysteam.module.user.dto.UserDTO;
import com.example.campussysteam.module.user.entity.Role;
import com.example.campussysteam.module.user.entity.User;
import com.example.campussysteam.module.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员教师管理控制器
 * 处理/api/admin/teacher相关请求
 */
@RestController
@RequestMapping("/api/admin/teacher")
@RequiredArgsConstructor
public class AdminTeacherController {

    private final UserRepository userRepository;

    /**
     * 搜索教师
     * @param query 搜索关键词
     * @return 教师列表
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('ADMIN')")
    @Log(module = "教师管理", type = OperationType.QUERY, description = "搜索教师")
    public ResponseEntity<List<UserDTO>> search(@RequestParam String query) {
        // 查询教师角色的用户
        List<User> teachers = userRepository.findByRoleAndRealNameContainingOrRoleAndUsernameContaining(
                Role.ROLE_TEACHER, query, Role.ROLE_TEACHER, query, 
                PageRequest.of(0, 10, Sort.by("id").descending())
        ).getContent();
        
        // 转换为DTO
        List<UserDTO> teacherDTOs = teachers.stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
                
        return ResponseEntity.ok(teacherDTOs);
    }
} 